//
// Created by 11510 on 2024/6/15.
//

#include "Dictionary.h"
#include <fstream>
#include <iostream>
#include <sstream>
using std::cin;
using std::cerr;
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::make_pair;
using std::string;
using std::map;

/**
 * 判断一个string是否是一个合法的单词
 * @param str
 * @return
 */
bool Dictionary::isWord(const std::string& str) {
    // 空字符串不是一个单词
    if (str.empty()) {
        return false;
    }
    // 遍历字符串中的每个字符，检查是否都是字母
    for (char c : str) {
        if (!std::isalpha(static_cast<unsigned char>(c))) {
            return false;
        }
    }
    return true;
}


void Dictionary::read(const std::string &filename) {
    ifstream ifs;
    ifs.open(filename);
    if(!ifs){
        cerr << "ifstream open file failed" << endl;
        return;
    }
    string line;
    /* 一行一行处理 */
    while(getline(ifs,line)){
        istringstream iss(line);
        string word;

        while(iss >> word){
            if(isWord(word)) {
                /* 雀食牛逼 */
                wordMap[word]++;
            }
        }
    }
}



void Dictionary::store(const string &filename){
    ofstream ofs(filename);
    if(!ofs){
        cerr << "ifstream open file failed" << endl;
        return;
    }

    for(std::map<string,int>::iterator it = wordMap.begin(); it != wordMap.end(); it++){
        ofs << it->first << ":" << it->second << endl;
    }
}